﻿/*
    Copyright (c) 2009 Chris Umbel

    Permission is hereby granted, free of charge, to any person obtaining a 
	copy of this software and associated documentation files (the "Software"), 
	to deal in the Software without restriction, including without limitation 
	the rights to use, copy, modify, merge, publish, distribute, sublicense, 
	and/or sell copies of the Software, and to permit persons to whom the Software 
	is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all 
	copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 
	FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 
	COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
	WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 
	IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.ReportingServices.Interfaces;
using Microsoft.ReportingServices.DataProcessing;
using System.Net;
using System.Globalization;
using System.Security.Cryptography;
using System.IO;
using System.Xml;
using System.Web;

namespace SimpleDBExtension
{
    public class SimpleDBConnection : IDbConnection
    {
        public void Dispose() { }

#region "Data Members"
        private string _accessKey;
        private string _secretKey;
#endregion

#region "Properties"
        public string AccessKey { get { return _accessKey; } }
        public int ConnectionTimeout { get; set; }
        public string LocalizedName { get; set; }
#endregion


#region "Methods"
        /* sign request with the secret key */
        public string SignRequest(string action, string timeStamp)
        {
            HMACSHA1 hash = new HMACSHA1();

            UTF8Encoding encoding = new UTF8Encoding();
            hash.Key = encoding.GetBytes(_secretKey);

            return Convert.ToBase64String(hash.ComputeHash(
                encoding.GetBytes(string.Format("{0}{1}", action, timeStamp).ToCharArray())));
        }

        /* semi-colon delimitation of access key and secret key */
        public string ConnectionString {
            get 
            {
                return string.Format("{0};{1}", _accessKey, _secretKey);
            }
            set 
            { 
                string[] keys = value.ToString().Split(';');
                _accessKey = keys[0].Trim();
                _secretKey = keys[1].Trim();
            }
        }

        public Microsoft.ReportingServices.DataProcessing.IDbCommand CreateCommand()
        {
            SimpleDBCommand cmd = new SimpleDBCommand();
            cmd.Connection = this;
            return cmd;
        }

        /* in the spirit of REST no connection state will be maintained */
        public void Open() 
        {
        }

        private string GetTimestamp()
        {
            return DateTime.UtcNow.ToString("s", System.Globalization.CultureInfo.InvariantCulture);
        }

        /* marshal post data */
        private string Encode(String data)
        {
            return HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(data));
        }

        /* create post to SimpleDB */
        internal string CreatePostData(string commandText, string nextToken)
        {
            string timeStamp = GetTimestamp();
            string action = "Select";

            string postData = string.Format("AWSAccessKeyId={0}&Timestamp={1}&Version={2}&SignatureVersion={3}&Signature={4}&Action={5}&SelectExpression={6}",
                    Encode(this.AccessKey),
                    Encode(timeStamp),
                    Encode("2007-11-07"),
                    Encode("0"),
                    Encode(SignRequest(action, timeStamp)),
                    Encode(action),
                    Encode(commandText));

            /* if a "next token is present include it in the command" */
            if (!nextToken.Equals(string.Empty))
                postData = string.Format("{0}&NextToken={1}", postData, Encode(nextToken));

            return postData;
        }

        /* send REST command to amazon */
        internal XmlDocument SendRequest(string commandText)
        {
            return this.SendRequest(commandText, string.Empty);
        }

        /* send REST command to amazon with next pointer */
        internal XmlDocument SendRequest(string commandText, string nextToken)
        {
            byte[] requestData = new UTF8Encoding().GetBytes(CreatePostData(commandText, nextToken));

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://sdb.amazonaws.com");
            request.UserAgent = "SSRS SimpleDBExtension";
            request.Method = "POST";
            request.Timeout = 50000;
            request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";   

            request.ContentLength = requestData.Length;

            /* write post data over the wire */
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(requestData, 0, requestData.Length);
            }

            /* read response from amazon */
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            XmlDocument results = new XmlDocument();

            /* read xml response from amazon */
            using (StreamReader resultsReader = new StreamReader(response.GetResponseStream()))
            {
                results.LoadXml(resultsReader.ReadToEnd());
            }

            return results;            
        }

        public void Close() { }

        public Microsoft.ReportingServices.DataProcessing.IDbTransaction BeginTransaction() { return null; }

        public void SetConfiguration(string configuration) { }
#endregion
    }
}
